<?php
/**
 * Super Simple and Convenient Persistent Storage Engine
 */ 
class ps_MetaBase {
  protected $data;  // In Memory Data Hash
  protected $driver; // ps_MetaBase_Driver
  protected $filters; // array of ps_MetaBase_Filter objects
  protected $debug = 0; // Level 0-9 Nine being the most 
  protected $defaultDriverConfig = array(
	'name'=>'Filesystem'
  );
  protected $config = array();

  /**
   * Class Constructor
   */
  public function __construct( $config=array(), $debugLevel=0 ) {
	if ( $debugLevel > 0) {
		$this->debug = $debugLevel;
		$this->debugger( 'Debugger level set to ' . $debugLevel );
	}

	if ( is_array( $config )) {
		$this->applyConfig( $config );
	}
	if ( isset( $config['driver'] ) ) {
	$this->loadDriver( $config['driver'] );
	} else  {
	$this->loadDriver( NULL );
	}
	if ( isset( $config['filters'] ) && count( $config['filters'] ) > 0 ) {
		foreach ( $config['filter'] as $name=>$config ) {
			$this->loadFilter( $name, $config );
		}
	}
  }

  /**
   * Quick Fetch no persistence
   */
  public function Fetch( $key ) {
	$this->debugger('->Fetch( ' . $key . ' )');
	return $this->data[$key];
  }

  /**
   * Fetch persistent stored data by $key
   * returns data or false if key is non-existent
   */
  public function pFetch( $key ) {
	$this->debugger('->pFetch( ' . $key . ' )');
	return $this->data[$key] = $this->driver->fetch( $key );
  }

  /**
   * Quick Store no persistence
   */
  public function Store( $key, $data ) {
	$this->debugger('->Store( ' . $key . ' )');
	$this->data[$key] = $data;
  }

  /**
   * Persistently Store $data by $key
   */
  public function pStore( $key, $data ) {
	$this->debugger('->pStore( ' . $key . ' )');
	$this->data[$key] = $data;
	return $this->driver->store($key, $data);
	
  }

  /**
   * load instance of ps_MetaBase_Driver_* into class
   */
  protected function loadDriver( $driverConfig ) {
    if ( !$driverConfig ) { 
	$this->debugger('Loading Default Driver Config', 9);
	$driverConfig = $this->defaultDriverConfig;
    }
    $classPrefix  = 'ps_MetaBase_Driver_';
    $driverClass = $classPrefix . $driverConfig['name'];
    $this->driver = new $driverClass( $driverConfig );	
  }

  /**
   * load instance of ps_MetaBase_Filter_* into $filters chain
   */
  protected function loadFilter( $name, $filterConfig ) {
    $this->debugger('Registering ' . $name . ' Filter', 9);
    $classPrefix  = 'ps_MetaBase_Filter_';
    $filterClass = $classPrefix . $name;
    $this->filters[$name] = new $filterClass( $filterConfig );	
    $this->filters[$name]->init();
  }

  /**
   * Merge config over the top of default config
   */
  protected function applyConfig( $config ) {
        $this->config = array_merge( $this->config, $config );
  } 

  /** 
   * debugger/logger method
   */
  protected function debugger( $data, $level=9 ) {
	if ( $level <= $this->debug ) {
		error_log (">>>>>>>>>>> Debug: " . $data );
        }
  }
}
?>
